import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router) 


const router = new Router({
  routes: [
    {
      path: '/login',
      name: 'login',
      component: ()=>import('@/views/login/index'),
      meta: { requiresAuth: false }
    },
    // {
    //   path: '/',
    //   name: 'homeIndex',
    //   component: ()=>import('@/views/home/index'),

    //   meta: { requiresAuth: true },
    //   children:[
    //     {
    //       path: '/home/tendency',
    //       name: 'tendency',
    //       component: ()=>import('@/views/home/tendency'),
    //       meta:{
    //         title:'项目趋势',
    //         requiresAuth: true 
    //       }
    //     }
    //   ]
    // },
  ]
})
/*生成首页路由-动态生成则无需在这里生成-未有动态路由时在这里生成;页面刷新时，需要重新生成路由*/
generateIndexRouter();


/*路由拦截器设置-before*/
router.beforeEach((to, from, next) => {
    // console.log(to,from)
    let token = sessionStorage.getItem('token')
    //1.登录权限判断
    if(to.meta.requiresAuth) {
        //验证token，存在才跳转
        if(token) {
            next()
        } 
        else {
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        }
    } 
    else{
        if(to.path === '/' ) {
            /*后退到login时拦截*/
            if(token){
                next({path:'/home/tendency'})
            }
            //根目录（刚进入页面时）
            else{
                next({path: '/login'})
            }
        }
        else{
          // alert(to.path)
            next()
        }
    }
    /*2.非登陆条件下输入某个地址 需要先跳到登录页再跳转到相应页面*/
    if(to.matched.length == 0 ){
        next({path: '/login',query: { redirect: to.fullPath }})
    }
});

router.afterEach((to, from) => {


})

// 生成首页路由
function  generateIndexRouter(){
        let indexRouter = {
          path: '/',
          name: "homeIndex",
          component:()=>import('@/views/home/index'),
          children: [
            ...generateChildRouters()
          ]
        }
        router.addRoutes([indexRouter])
    }

// 生成嵌套路由（子路由）
function generateChildRouters() {
  let that = this
            //如果还没有存在 需要返回一个空对象，否则会报错 Cannot convert undefined or null to object 因为children数组中存的值不能为undefined
            if (!window.sessionStorage.getItem('routers')) {
                return {}
            }

            let routers = JSON.parse(sessionStorage.getItem('routers'))
            // console.log(routers)
            /*子路由数组，最后由函数return*/
            let childRouters = []
            /*初始化按钮访问权限*/
            // let button_limit = [] 

            for(let router of routers) {
                try {
                  /*路由存储*/
                  if(router.isRouter == '1'  ){
                       let childRouter = {
                          path: JSON.parse(router.routerCode).path,
                          name: JSON.parse(router.routerCode).name,
                          component:resolve => require(['@/' + JSON.parse(router.routerCode).component.slice(2)], resolve), //  ()=>import('@/views/homework/index')不  routerProps.component , //resolve => require([routerProps.component], resolve)不
                          // meta: {title:meta,requiresAuth:true}
                          meta:JSON.parse(router.routerCode).meta
                      }
                      // console.log( childRouter)
                      childRouters.push(childRouter) 
                  }
                  /*页面操作权限存储*/
                  if(router.isMenu == '0'){ 
                      // button_limit.push(router)
                  }
                }catch (ex) {
                    console.warn(ex.message)
                }
            }
            // that.$store.commit("setbutton_limit",button_limit);
            // console.log(childRouters,'active......')
            return childRouters
}
 


export default router